import Player from "../player/Player";
import PlayerManager from "../manager/PlayerManager";
import Dialog from "./Dialog";
import { Global } from "../info/Global";
import { FacilityType, GamePropType } from "../info/GameEnum";
import Launchable from "../funcObj/interface/Launchable";
import ScoutReserve from "../prop/ScoutReserve";
import FlareReserve from "../prop/FlareReserve";
import { Location } from "../info/Predefine";
import NoviceGuide from "../UI/NoviceGuide";
import GameManager from "../manager/GameManager";
import LaunchableFalicity from "../facility/LaunchableFalicity";
import MusicManager from "../../MusicManager";
import DispatchDialogScene from "../../scene/dialog/DispatchDialogScene";
import ControlledPlayer from "../player/ControlledPlayer";

const { ccclass, property } = cc._decorator;

/**
 * 派遣弹窗
 */
@ccclass
export default class DispatchDialog extends Dialog {

    @property(cc.Label)
    title: cc.Label = null;

    @property(cc.Node)
    item: cc.Node = null;

    @property(cc.Node)
    itemParent: cc.Node = null;

    @property(cc.Node)
    nothingTip: cc.Node = null;

    @property(cc.Button)
    domainExpander: cc.Button = null;

    location: Location;
    player: Player
    isHide: boolean;

    controllerPlayer: ControlledPlayer;

    protected onEnable(): void {
        this.controllerPlayer = PlayerManager.instance.controllerPlayer;
        this.controllerPlayer.node.on(Player.EventType.更新飞行物数量, this.refreshButton, this);
    }

    protected onDisable(): void {
        cc.isValid(this.controllerPlayer) && this.controllerPlayer.node.targetOff(this);
        cc.find("img_blackBorder", this.node).targetOff(this);
    }

    public init(location: Location, isHide: boolean) {
        this.location = location;
        this.player = PlayerManager.instance.controllerPlayer;
        this.isHide = isHide;
        this.title.string = isHide ? "未探索区域" : "可发射";

        for (const key in FacilityType) {
            let facType = FacilityType[key];
            if (typeof facType == "number") {
                let ex = this.itemParent.children.find(item => item["facilityType"] == facType);
                this.addButton(facType, ex);
            }
        }

        let img_blackBorder = cc.find("img_blackBorder", this.node);
        img_blackBorder.on(cc.Node.EventType.SIZE_CHANGED, () => {
            this.title.node.parent.y = img_blackBorder.height / 2;
        }, this);

        if (!this.itemParent.children.find(item => item.active)) {
            this.itemParent.height = 0;
        }

        this.resetDomainExpander();

        this.nothingTip.active = !this.itemParent.children.find(item => item.active);
    }

    addButton(facilityType: FacilityType, ex: cc.Node) {
        let facilityInfo = Global.getFacilityInfo<{ 射程半径: number, 飞行物名字: string }>(facilityType)
        if (!facilityInfo || !facilityInfo.飞行物名字) return;
        let count = this.player.getAllFlyerCountByFacilityType(facilityType);
        if (!this.player.facilityArr[facilityType].length && count == 0) {
            return ex && (ex.active = false)
        }

        let list: Launchable[] = this.player.facilityArr[facilityType].concat() as unknown as Launchable[];
        if (facilityType == FacilityType.侦察机基地) {
            let sr = this.player.facilityArr[FacilityType.主基地][0].getComponentInChildren(ScoutReserve)
            if (sr) {
                list.push(sr);
            }
        }
        if (facilityType == FacilityType.照明弹基地) {
            let fr = this.player.facilityArr[FacilityType.主基地][0].getComponentInChildren(FlareReserve)
            if (fr) {
                list.push(fr);
            }
        }

        let inRangeFac = list.find(fac => {
            let disX = Math.abs(fac.locations[0].locationX - this.location.locationX),
                disY = Math.abs(fac.locations[0].locationY - this.location.locationY);
            let distance = Math.round(Math.sqrt(disX * disX + disY * disY));
            return fac.count > 0 && fac.shotRange >= distance
        })

        let newItem = ex ?? cc.instantiate(this.item);
        newItem.active = true;
        newItem.parent = this.itemParent;
        newItem.name = facilityInfo.飞行物名字;
        newItem["facilityType"] = facilityType;
        newItem.active = true;
        let newItemLabels = newItem.getComponentsInChildren(cc.Label);
        newItemLabels[0].string = facilityInfo.飞行物名字 + "×" + count;
        newItemLabels[1].node.active = false;
        newItem.getComponent(cc.Button).interactable = false;
        if (inRangeFac) {
            newItem.getComponent(cc.Button).interactable = true;
        } else if (count > 0) {
            //如果没有在射程内又有炮弹的，找最近的没有炮弹的设施显示超出射程
            let nearFac: { fac: Launchable, distance: number } = null;
            list.forEach((fac) => {
                let disX = Math.abs(fac.locations[0].locationX - this.location.locationX),
                    disY = Math.abs(fac.locations[0].locationY - this.location.locationY);
                let distance = Math.round(Math.sqrt(disX * disX + disY * disY));
                if (nearFac === null || distance < nearFac.distance && nearFac.fac.count == 0) {
                    nearFac = { fac: fac, distance: distance };
                }
            })
            let shotRange = nearFac.fac.shotRange;
            newItemLabels[1].node.active = true;
            newItemLabels[1].string = "超出射程" + Math.ceil(shotRange - nearFac.distance) + "米";
        }
    }

    public closeDialog(): void {
        this.node.active = false;
    }

    refreshButton(facilityType: FacilityType) {
        let facilityInfo = Global.getFacilityInfo<{ 飞行物名字: string }>(facilityType);
        let itemNode = this.itemParent.getChildByName(facilityInfo.飞行物名字);
        this.addButton(facilityType, itemNode);
        if (!this.itemParent.children.find(item => item.active)) {
            this.itemParent.height = 0;
        }
    }

    resetDomainExpander() {
        if (this.player.props[GamePropType.飞地]) {
            if (!this.isHide && !GameManager.instance.getFacilityByLocation(this.location)) {
                let result = PlayerManager.instance.controllerPlayer.checkFacilityCondition(FacilityType.领土扩张器);
                this.domainExpander.node.active = result[2];
                if (!this.domainExpander.node.active) return;
                let price = PlayerManager.instance.controllerPlayer.getPrice(FacilityType.领土扩张器);
                let priceNode = this.domainExpander.node.getChildByName("price");
                let diamondNode = priceNode.getChildByName("diamond");
                let oilNode = priceNode.getChildByName("oil");
                let limitTip = this.domainExpander.node.getChildByName("已达上限");

                diamondNode.active = price.diamond > 0;
                oilNode.active = price.oil > 0;
                diamondNode.getComponentInChildren(cc.Label).string = price.diamond.toString();
                oilNode.getComponentInChildren(cc.Label).string = price.oil.toString();
                limitTip && (limitTip.active = !result[3], priceNode.active = !limitTip.active);
                this.domainExpander.interactable = priceNode.active && result[0] && result[1];
            } else {
                this.domainExpander.node.active = false;
            }
        } else {
            if (this.domainExpander) {
                this.domainExpander.node.parent = this.node;
                this.domainExpander.node.destroy();
                this.domainExpander = null;
            }
        }
    }

    onClick(event: cc.Event) {
        let desFacility = this.player.dispatchFlyer(event.target["facilityType"], this.location);
        MusicManager.instance.play(MusicManager.instance.btnMove);
        //新手引导
        if (event.target["facilityType"] == FacilityType.侦察机基地) {
            this.player.node.emit(NoviceGuide.EventType.派遣侦察机);
        } else {
            if (this.player.isLocationVisible(this.location) && GameManager.instance.getFacilityByLocation(this.location)) {
                if (desFacility instanceof LaunchableFalicity) {
                    this.player.node.emit(NoviceGuide.EventType.给敌人建筑发射一枚炮弹);
                }
            }
        }
    }

    onClickDomainExpander() {
        MusicManager.instance.play(MusicManager.instance.btnMove);
        this.player.addFacility(FacilityType.领土扩张器, [this.location]);
        this.closeDialog();
    }
}
